package main

import (
	"fmt"
	"sync"
	"time"
)

func defineChannelType() {
	var ch1 chan int // 声明一个传递整型的通道
	//var ch2 chan bool // 声明一个传递布尔型的通道
	//var ch3 chan []int // 声明一个传递int切片的通道

	ch1 = make(chan int, 1)

	ch1 <- 10 //把10发送到ch1中

	x := <-ch1 //从ch1中接收值并赋值给变量 x
	//<- ch1 //从ch1中接收值，并忽略结果

	fmt.Println(x) // 10

	close(ch1) //关闭ch1

	x1 := <-ch1
	fmt.Println(x1) // 0
}

func recv(ch chan int) {
	x := <-ch
	fmt.Println("接收成功", x)
}

//单向发送
func counter(in chan<- int) {
	for i := 0; i < 10; i++ {
		in <- i
	}
	close(in)
}

//单向接收或发送
func squarer(in chan<- int, out <-chan int) {
	for i := range out {
		in <- i * i
	}
	close(in)
}

func workerPool(id int, jobs <-chan int, results chan<- int) {
	for job := range jobs {
		fmt.Printf("worker:%d start job:%d \n", id, job)
		time.Sleep(time.Second)
		fmt.Printf("worker:%d, end job:%d \n", id, job)
		results <- job
	}
	close(results)
}

func reduce() {
	for i := 0; i < 5000 && x > 0; i++ {
		lock.Lock()
		x = x - 1
		lock.Unlock()
	}
	wg.Done()
}

func write() {
	rwlock.Lock() // 加写锁
	x = x + 1
	time.Sleep(10 * time.Millisecond)
	rwlock.Unlock()
	wg.Done()
}

func read() {
	rwlock.RLock() // 加写锁
	time.Sleep(time.Millisecond)
	fmt.Println(x)
	rwlock.RUnlock()
	wg.Done()
}

var x int64 = 0
var wg sync.WaitGroup
var lock sync.Mutex
var rwlock sync.RWMutex

func channelMain() {
	start := time.Now()
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go write()
	}
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go read()
	}

	wg.Wait()
	end := time.Now()
	fmt.Println(end.Sub(start)) // 174.30ms
	fmt.Println(x)              // 174.30ms
}
